package com.example.shengyin.frontController;
import com.example.shengyin.entity.User;
import com.example.shengyin.entity.User2;
import com.example.shengyin.entity.User3;
import com.example.shengyin.service.UserService;
import com.example.shengyin.util.Md5Utils;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.SMSClient;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * AdminController
 *
 * @author ruoyi
 * @date 2023-07-29
 */
@RestController
@RequestMapping("/front/user")
@Validated
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials="true")
//swagger
@Api(tags = "FrontUserController", description = "用户登录注册等")
public class FrontUserController
{
    @Autowired
    private UserService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @ApiOperation("登录需要先获取验证码，成功后会返回一个数据，下次要带上，放在全请求头里，作为value,key命名为Authorization")
    @PostMapping("/login")
    public Result userLogin(String root, String pass, String code, HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if(authorization==null)
            return Result.error("请携带请求头");
        String code2 = (String) redisTemplate.opsForValue().get(authorization);
        if(code2==null)
            return Result.error("验证码为空");
        if(!code.equals(code2)){
            return Result.error("验证码输入错误");
        }
        User login = service.login(root, Md5Utils.hash(pass));
        if(login==null)
            return Result.error("错误的用户名或者密码!");
        if(login.getIsvalid()==0)
            return Result.error("用户不合法，无法登录，如有疑问请联系管理员!");
        HttpSession session = request.getSession();
            redisTemplate.opsForValue().set(authorization,login,200, TimeUnit.MINUTES);
            return Result.success(authorization,"登录成功");
    }
    @ApiOperation("获得验证码")
    @GetMapping("/getCode")
    public Object genCode(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        response.reset();
        response.setContentType( "image/jpeg" );
        //图像数据缓冲区
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        //绘制图片
        Graphics g = bi.getGraphics();
        //获取颜色
        Color c = new Color(150, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        //生成随机数
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("code", sb.toString());
        //输出图片
        //前3个，设置不缓存
        response.setHeader( "Prama", "no-cache");
        response.setHeader( "Cache-Control", "no-cache" );
        response.setDateHeader( "Expires", 0);
        //设置内容类型
        return ImageIO.write(bi, "JPG", response.getOutputStream());
    }
    //private static  BASE64Encoder base64Encoder = new BASE64Encoder();
    //base64转换


    @ApiOperation("获得验证码,这种格式的//$(\".codeImage\")[0].src=\"data:image/png;base64,\"+r.data;")
    @GetMapping("/getAjaxCode")
    public Result vcode(HttpServletRequest request) throws ServletException, IOException {

        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200, 155, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        FastByteArrayOutputStream bout = new FastByteArrayOutputStream();
        ImageIO.write(bi, "JPG", bout);
        String key= UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key,sb.toString(),200, TimeUnit.MINUTES);
        Map<String,String > map=new HashMap<>();
        String uid=UUID.randomUUID().toString();
        map.put("Authorization",key);
        map.put("picbase64",StrUtil.toBase64(bout.toByteArray()));
        request.getSession().setAttribute("code", sb.toString());
        return Result.success(map);
        /*以前是这样用
        <img src="xxxx/gencode" />
        //现在是这样
        $.get(BASE_URL+"genCode.cmd?"+Math.random(),function(r){

					key=r.msg;
					$(".codeImage").attr("src","data:image/png;base64,"+r.data);
					//$(".codeImage")[0].src="data:image/png;base64,"+r.data;
				});
         */
    }

    @ApiOperation("个人信息获取")
    @GetMapping("/getInfo")
    public Result select(HttpServletRequest request) {

        System.out.println(request.getHeader("Authorization"));
        if(request.getHeader("Authorization")==null)
            return Result.error("请先登录");
        User user = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(user==null)
            return Result.error("请先登录");
        user.setPass(null);
        return Result.success(user,"获取成功");
    }



    @ApiOperation("获取手机短信验证码")
    @GetMapping("/getPhoneCode")
    public Result select(@ApiParam(name = "phone",value = "手机号") @RequestParam(required = true) String phone,
    @ApiParam(name = "pass",value = "我设置的密码") @RequestParam(required = true) String pass) {
        if(!(pass.equals("bdqnaccp")))
        {
            return Result.error("密码不对");
        }
        long code=System.currentTimeMillis()%10000;
        SMSClient.sendMsm(phone,"本次验证码为"+code+",请在5分钟内输入");
        String key= UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key,String.valueOf(code),200, TimeUnit.MINUTES);
        Map<String,String > map=new HashMap<>();
        map.put("Authorization",key);
        return Result.success(map,"获取成功");
    }
    @ApiOperation("注册需要先获取验证码")
    @PostMapping("/add")
    public Result insert(User3 dAdmin, String code, HttpServletRequest request)
    {
        User user=new User();
        user.setUname(dAdmin.getUname());
        user.setPhone(dAdmin.getPhone());
        user.setPass(dAdmin.getPass());
        String authorization = request.getHeader("Authorization");
        if(authorization==null)
            return Result.error("请携带请求头");
        String code2 = (String) redisTemplate.opsForValue().get(authorization);
        if(code2==null)
            return Result.error("验证码为空");
        if(!code.equals(code2)){
            return Result.error("验证码输入错误");
        }
        User user2 = service.selectByPhoneandName(dAdmin.getUname(),null);
        if(user2!=null)
        {
            return Result.error("该用户名已被注册");
        }
        user2 = service.selectByPhoneandName(null,dAdmin.getPhone());
        if(user2!=null)
        {
            return Result.error("该手机号已被注册");
        }
        user.setPass(Md5Utils.hash(dAdmin.getPass()));
        int insert = service.insert(user);
        if(insert==0)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }
    @ApiOperation("更新")
    @PostMapping("/edit")
    public Result edit(@Valid User2 dAdmin2, @ApiParam(name = "password",value = "该密码的时候要输入") @RequestParam(required = false) String password, BindingResult bindingResult , HttpServletRequest request)
    {
        User dAdmin=new User();
        dAdmin.setId(dAdmin2.getId());
        dAdmin.setUname(dAdmin2.getUname());
        dAdmin.setPass(dAdmin2.getPass());
        dAdmin.setAvator(dAdmin2.getAvator());
        dAdmin.setPersonlabel(dAdmin2.getPersonlabel());
        dAdmin.setQq(dAdmin2.getQq());
        dAdmin.setWeibo(dAdmin2.getWeibo());
        System.out.println(request.getHeader("Authorization"));
        User admin = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin==null)
        {
            return Result.error("请先登录");
        }
        if(admin.getId()!=dAdmin.getId())
        {
            return Result.error("不是本人操作，无法更新");
        }
        if(dAdmin.getPass()!=null)
        {
            System.out.println(request.getHeader("Authorization"));
            if(request.getHeader("Authorization")==null)
                return Result.error("请先登录");
            User user = (User) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
            if(user==null)
                return Result.error("请先登录");
            if (user.getId()!=dAdmin.getId())
                return Result.error("您修改的不是自己的信息");
            if(user.getPass()!=password)
                return Result.error("您的密码不正确，请输入正确的密码");
        }
        int insert = service.update(dAdmin);
        if(insert==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }
}
